package com.gopay.scheduler.service.qualifications.impl;

import com.gopay.common.constants.mail.MailLevel;
import com.gopay.common.constants.mail.MailSendType;
import com.gopay.common.constants.mail.MailTemplateType;
import com.gopay.common.domain.cust.CustCorpInfo;
import com.gopay.common.domain.cust.CustInfoAudit;
import com.gopay.common.domain.mail.SendWithAttachment;
import com.gopay.common.user.dao.CustCorpInfoQueryDAO;
import com.gopay.common.util.JsonUtils;
import com.gopay.cron.web.vo.OverQualificationsInfoVo;
import com.gopay.remote.cps.mail.MailRemoteService;
import com.gopay.scheduler.dao.qulifications.CustInfoAuditReadDao;
import com.gopay.scheduler.dao.qulifications.MessageSendReadDao;
import com.gopay.scheduler.dao.qulifications.OverQualificationsInfoReadDao;
import com.gopay.scheduler.service.qualifications.OverQualificationsInfoService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * CLASSNAME:OverQualificationsInfoServiceImpl
 * Description:资质过期服务实现类
 * DATE:2017/5/4/004
 * AUTHER:PANSHICHAO
 * www.gopay.com.cn Inc.All rights reserved.
 */
@Service("overQualificationsInfoService")
public class OverQualificationsInfoServiceImpl implements OverQualificationsInfoService {
    @Autowired
    private OverQualificationsInfoReadDao overQualificationsInfoReadDao;
    @Resource(name="mailRemoteService")
    private MailRemoteService mailRemoteService;
    @Resource(name="messageSendReadDao")
    private MessageSendReadDao messageSendReadDao;
    @Resource(name="custInfoAuditReadDao")
    private CustInfoAuditReadDao custInfoAuditReadDao;
    @Resource(name="custCorpInfoQueryDao")
    private CustCorpInfoQueryDAO custCorpInfoQueryDAO;
    protected Logger logger = LoggerFactory.getLogger(OverQualificationsInfoServiceImpl.class);
    @Override
    public void sendMail(String email) throws Exception{
        String fileFullName = createExcelInfoByResultList(showAllOverQualificationsInfo(email));
        if(StringUtils.isNotBlank(fileFullName)){
            String fileName =fileFullName.split(",")[1];
            SendWithAttachment send = new SendWithAttachment();
            send.setSendType(MailSendType.MAIL_SEND_TYPE_WITH_ATTACHMENT);
            send.setLevel(MailLevel.HIGH);
            send.setTemplate(MailTemplateType.RC_QULIFICATIONS_INFO_NOTIFY.value);
            send.setReceivers(email);
            Map<String,String> content = new HashMap<String,String>();
            Map<String,String> attachemnts = new HashMap<String,String>();
            attachemnts.put(fileName,"upload/qualification/"+new SimpleDateFormat("yyyyMMdd").format(new Date())+"/"+fileName);
            try {
                send.setAttachments(JsonUtils.toJson(attachemnts));
                send.setContent(JsonUtils.toJson(content));
            } catch (IOException e) {
                logger.error("json字符窜格式化异常",e);
            }
            int i = mailRemoteService.addMailWithAttachmentTask(send);
            logger.error("邮件发送结果为:"+i);
        }
    }

    private String createExcelInfoByResultList(List<OverQualificationsInfoVo> resultList) throws Exception {
        if (resultList != null && resultList.size() > 0) {
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("资质过期信息表");
            sheet.setDefaultColumnWidth((short) 16);
            String[] titles = new String[]{"客户ID", "客户名称", "Email", "是否为商户", "资质类型", "资质有效期"};
            HSSFRow titleRow = sheet.createRow(0);
            // 创建HSSFCellStyle实例，并设置上边框、下边框的样式
            HSSFCellStyle style = workbook.createCellStyle();
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            // 创建HSSFFont实例，设置字体、字号、加粗、颜色
            HSSFFont font = workbook.createFont();
            font.setFontName(HSSFFont.FONT_ARIAL);// 字体
            font.setFontHeightInPoints((short) 10);// 字号
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗
            font.setColor(HSSFColor.BLACK.index);// 颜色
            style.setFont(font);
            String fileName = new SimpleDateFormat("yyyy年MM月dd日").format(new Date()) + "资质即将到期的企业名单.xls";
            String filePath = "/usr/local/ciecc/webapps/upload/qualification/"+new SimpleDateFormat("yyyyMMdd").format(new Date())+"/";
            logger.error("文件夹位置："+filePath);
            logger.error("文件名称："+fileName);
            File file = new File(filePath);
            if(!file.exists()){
                if(!file.mkdirs()){
                    throw new IOException();
                }
            }
            // 设置列表头信息
            for (int i = 0; i < titles.length; i++) {
                HSSFCell cell = titleRow.createCell((short) i);
                cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                cell.setCellValue(new HSSFRichTextString(titles[i]));
                cell.setCellStyle(style);
            }
            // 填充内容
            int rowNum = 1;
            for (OverQualificationsInfoVo vo : resultList) {
                HSSFRow crow = sheet.createRow(rowNum++);
                crow.createCell((short) 0).setCellValue(new HSSFRichTextString(vo.getCustId()));
                crow.createCell((short) 1).setCellValue(new HSSFRichTextString(vo.getCustName()));
                crow.createCell((short) 2).setCellValue(new HSSFRichTextString(vo.getEmail()));
                crow.createCell((short) 3).setCellValue(new HSSFRichTextString(vo.getIsCust()));
                crow.createCell((short) 4).setCellValue(new HSSFRichTextString(vo.getQualificationName()));
                crow.createCell((short) 5).setCellValue(new HSSFRichTextString(vo.getQualificationTerm()));
            }
            OutputStream out = null;
            try {

                out = new FileOutputStream(filePath + fileName);
                workbook.write(out);
                out.close();
                return filePath+","+fileName;
            } catch (Exception e) {
                logger.error("凭证到期附件生成失败:"+e);
            }
        }
        return null;
    }
    private List<OverQualificationsInfoVo> showAllOverQualificationsInfo(String email){
        List<OverQualificationsInfoVo> resultList = new ArrayList<OverQualificationsInfoVo>();
        Date [] dates = showTimeIntervalToGetOverQualificationsInfo(email);
        Date nowDate = dates[0];
        Date endDate = dates[1];
        List<Object[]> result1 = overQualificationsInfoReadDao.getAllBusinessTermOverQualificationsInfo(nowDate,endDate);
        List<Object[]> result2 = overQualificationsInfoReadDao.getAllLegalPersonCertTermOverQualificationsInfo(nowDate,endDate);
        if (result1 != null) {
            for(Object[] obj : result1){
                OverQualificationsInfoVo vo = new OverQualificationsInfoVo();
                if(obj[0] !=null){
                    vo.setCustId(obj[0].toString());
                }else{
                    vo.setCustId("");
                }
                if(obj[1] !=null){
                    vo.setCustName(obj[1].toString());
                }else{
                    vo.setCustName("");
                }
                if(obj[2] !=null){
                    vo.setEmail(obj[2].toString());
                }else{
                    vo.setEmail("");
                }
                if(obj[4] !=null){
                    if(obj[4].toString().equals("0")){
                        vo.setIsCust("否");
                    }else{
                        vo.setIsCust("是");
                    }
                }else{
                    vo.setIsCust("");
                }
                vo.setQualificationName("营业执照");
                if(obj[3] != null){
                    SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
                    String transDate = format.format(obj[3]);
                    vo.setQualificationTerm(transDate);
                }else{
                    vo.setQualificationTerm("");
                }
                resultList.add(vo);
            }
        }

        if(result2 != null){
            for(Object[] obj : result2){
                OverQualificationsInfoVo vo = new OverQualificationsInfoVo();
                if(obj[0] !=null){
                    vo.setCustId(obj[0].toString());
                }else{
                    vo.setCustId("");
                }
                if(obj[1] !=null){
                    vo.setCustName(obj[1].toString());
                }else{
                    vo.setCustName("");
                }
                if(obj[2] !=null){
                    vo.setEmail(obj[2].toString());
                }else{
                    vo.setEmail("");
                }
                if(obj[4] !=null){
                    if(obj[4].toString().equals("0")){
                        vo.setIsCust("否");
                    }else{
                        vo.setIsCust("是");
                    }
                }else{
                    vo.setIsCust("");
                }
                vo.setQualificationName("法人证件");
                if(obj[3] != null){
                    SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
                    String transDate = format.format(obj[3]);
                    vo.setQualificationTerm(transDate);
                }else{
                    vo.setQualificationTerm("");
                }
                resultList.add(vo);
            }
        }
        Date startTime = new Date();
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(startTime);
        calendar.add(Calendar.DAY_OF_YEAR,13);
        Date endTime =  calendar.getTime();
        List<CustInfoAudit> businessTermResult = custInfoAuditReadDao.getAllBusinessTermUpdateInfosBetweenCycle(startTime,endTime);
        List<CustInfoAudit> legalPersonCertTermResult = custInfoAuditReadDao.getAllLegalPersonCertTermUpdateInfosBetweenCycle(startTime,endTime);
        if(businessTermResult !=null){
            if(businessTermResult.size() != 0){
                for(CustInfoAudit custInfoAudit : businessTermResult){
                    logger.error("用户ID："+custInfoAudit.getCustId());
                    String custId = custInfoAudit.getCustId();
                    CustCorpInfo custCorpInfo =custCorpInfoQueryDAO.getByCustId(custId);
                    if(("1").equals(custCorpInfo.getIsRealNameCertify())){
                        OverQualificationsInfoVo vo = new OverQualificationsInfoVo();
                        if(StringUtils.isNotBlank(custCorpInfo.getCorpName())){
                            vo.setCustName(custCorpInfo.getCorpName());
                        }else{
                            vo.setCustName("");
                        }
                        if(StringUtils.isNotBlank(custCorpInfo.getEmail())){
                            vo.setEmail(custCorpInfo.getEmail());
                        }else{
                            vo.setEmail("");
                        }
                        vo.setCustId(custCorpInfo.getCustId());
                        vo.setQualificationName("营业执照");
                        String overTime = custInfoAudit.getFieldAfter();
                        if(StringUtils.isNotBlank(overTime)){
                            String [] arrays = overTime.split("-");
                            overTime = arrays[0]+"年"+arrays[1]+"月"+arrays[2]+"日";
                        }
                        logger.error("格式化后的日期字符窜为:"+overTime);
                        vo.setQualificationTerm(overTime);

                        if(("0").equals(custCorpInfo.getIsMerChant())){
                            vo.setIsCust("否");
                        }else{
                            vo.setIsCust("是");
                        }
                        resultList.add(vo);
                    }else{
                        continue;
                    }
                }
            }
        }
        if(legalPersonCertTermResult !=null){
            if(legalPersonCertTermResult.size() != 0){
                for(CustInfoAudit custInfoAudit : legalPersonCertTermResult){
                    logger.error("用户ID："+custInfoAudit.getCustId());
                    String custId = custInfoAudit.getCustId();
                    CustCorpInfo custCorpInfo =custCorpInfoQueryDAO.getByCustId(custId);
                    logger.error("证件过期时间:"+custCorpInfo.getLegalPersonCertTerm());
                    if(("1").equals(custCorpInfo.getIsRealNameCertify())){
                        OverQualificationsInfoVo vo = new OverQualificationsInfoVo();
                        if(StringUtils.isNotBlank(custCorpInfo.getCorpName())){
                            vo.setCustName(custCorpInfo.getCorpName());
                        }else{
                            vo.setCustName("");
                        }
                        if(StringUtils.isNotBlank(custCorpInfo.getEmail())){
                            vo.setEmail(custCorpInfo.getEmail());
                        }else{
                            vo.setEmail("");
                        }
                        vo.setCustId(custCorpInfo.getCustId());
                        vo.setQualificationName("法人证件");
                        String overTime = custInfoAudit.getFieldAfter();
                        if(StringUtils.isNotBlank(overTime)){
                            String [] arrays = overTime.split("-");
                            overTime = arrays[0]+"年"+arrays[1]+"月"+arrays[2]+"日";
                        }
                        logger.error("格式化后的日期字符窜为:"+overTime);
                        vo.setQualificationTerm(overTime);

                        if(("0").equals(custCorpInfo.getIsMerChant())){
                            vo.setIsCust("否");
                        }else{
                            vo.setIsCust("是");
                        }
                        resultList.add(vo);
                    }else{
                        continue;
                    }
                }
            }
        }
        return resultList;
    }

    private Date[] showTimeIntervalToGetOverQualificationsInfo(String email){
       Date[] dates = new Date[2];
       List<Object[]> resultList = messageSendReadDao.getSendMailDateInfo(email);
       if(resultList !=null && resultList.size() != 0){
           Date dateStr = (Date)resultList.get(0)[0];
           Date newDate = new Date();
           Calendar calendar = Calendar.getInstance();
           calendar.setTime(dateStr);
           int day1 = calendar.get(Calendar.DAY_OF_YEAR);
           calendar.add(Calendar.DAY_OF_YEAR,14);
           Date nowDate = calendar.getTime();
           dates[0] = nowDate;
           calendar.setTime(newDate);
           int day2 = calendar.get(Calendar.DAY_OF_YEAR);
           int i = day2-day1;
           calendar.setTime(nowDate);
           calendar.add(Calendar.DAY_OF_YEAR,i);
           Date endDate = calendar.getTime();
           dates[1] = endDate;
           return dates;
       }else{
           Date nowDate = new Date();
           Calendar calendar = Calendar.getInstance();
           calendar.setTime(nowDate);
           calendar.add(Calendar.DAY_OF_YEAR,14);
           Date endDate = calendar.getTime();
           dates[0]=nowDate;
           dates[1]= endDate;
       }
       return dates;
    }

}
